package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Slf4j
@Api(tags = "地址接口")
public class UserAddressController {

    @Autowired
    private AddressService addressService;
    @PostMapping
    public Result add(@RequestBody AddressBook addressBook){
        addressService.add(addressBook);
        return Result.success();
    }
    @GetMapping("/list")
    public Result<List<AddressBook>> list(){
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressService.list(addressBook);
        return Result.success(list);
    }

    @GetMapping("/default")
    public Result<AddressBook>  selectDefault(){
        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(1);
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressService.list(addressBook);

        if (list != null && list.size() == 1) {
            return Result.success(list.get(0));
        }

        return Result.error("没有查询到默认地址");
    }
    @PutMapping
    public Result update(@RequestBody AddressBook addressBook){
        addressService.update(addressBook);
        return Result.success();

    }
    @DeleteMapping
    public Result deleteById(Long id){
        addressService.deleteById(id);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result<AddressBook> getById(@PathVariable Long id) {
        AddressBook addressBook = addressService.getById(id);
        return Result.success(addressBook);
    }
    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result setDefault(@RequestBody AddressBook addressBook) {
        addressService.setDefault(addressBook);
        return Result.success();
    }

}

